"""
解析数据到智图和A表
"""
import os
import shutil
import sys

import facade
from parsel import Selector
from xjlibrary.mdatetime.mtime import getTodayDate
from xjlibrary.mdatetime.mtime2 import MDateTimeUtils
from xjlibrary.our_file_dir import BaseDir
from xjlibrary.tools.BaseString import BaseString

from id_encode import GetLngid

curpath = BaseDir.get_file_dir_absolute(__file__)
TopPath = BaseDir.get_upper_dir(curpath, -2)
dirPath = BaseDir.get_new_path(TopPath, "download", "yuetong_bz", "download", "bzhtml")
db3dir = BaseDir.get_new_path(TopPath, "download", "yuetong_bz", "download", "db3")
BaseDir.create_dir(db3dir)
configfile = BaseDir.get_new_path(curpath, "db.ini")
sPath = BaseDir.get_new_path(curpath, "template")


class ParaZTA(object):
    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutils = facade.MysqlUtiles(configfile, "db", logger=self.logger)
        self.Listpara = []
        self.templatedb3 = BaseDir.get_new_path(sPath, "zt_template.db3")
        self.new_db3_path = self.copyTempDB3(self.templatedb3, db3dir)
        self.db3_zt = facade.Sqlite3Utiles(logger=self.logger).Sqlite3DBConnectFromFilePath(
            self.new_db3_path, encoding="utf-8")

    def copyTempDB3(self, temp_path, copy_out):
        """
        拷贝创建新的db3文件
        :param temp_path: 模板db3文件路径
        :param copy_out: 新的db3输出路径
        :return: 新db3路径
        """
        today_str = str(getTodayDate())
        if not os.path.isfile(temp_path) or not os.path.isdir(copy_out):
            raise FileNotFoundError
        new_db3_name = 'zt_yuetongstandard_' + today_str + '.db3'
        new_db3_path = os.path.join(copy_out, new_db3_name)
        shutil.copyfile(temp_path, new_db3_path)
        return new_db3_path

    def select_files(self):
        for file in BaseDir.get_dir_all_files(dirPath):
            print(file)
            rawid = file.split("\\")[-1].replace(".html", "")
            html = BaseDir.single_read_file(file)
            self.para_html(html, rawid)
        self.insert_db3()

    def insert_db3(self):
        sql = "insert or ignore into modify_title_info_zt (`lngid`,`rawid`,`title`,`country`,`language`,`provider`,`batch`," \
              "`type`,`medium`,`provider_url`,`provider_id`,`date`,`date_created`,`publisher`," \
              "`creator_release`,`description`,`description_type`,`date_impl`,`legal_status`, `creator_drafting`, `creator`, `pagecount`,`page`,`title_alternative`) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"

        self.db3_zt.ExeSqlliteMany(sql, self.Listpara)
        self.Listpara.clear()

    def para_html(self, html, rawid):
        select = Selector(text=html)
        div_tag_list = select.xpath('.//div[@class="minbox"]/div[@class="minboxtit"]')
        title = ""
        legal_status = ""
        title_alternative = ""
        date_created = ""
        date_impl = ""
        creator_release = ""
        creator_drafting = ""
        creator = ""
        description = ""
        page = ""
        publisher = ""
        description_type = ""
        for div_tag in div_tag_list:
            strings = "".join(div_tag.xpath(".//text()").getall())
            strings = strings.strip()
            if strings.find("【标准名称】：") > -1:
                title = strings.replace("【标准名称】：", "").strip()
            elif strings.find("【书号】：") > -1:
                # 不用 丢弃
                shuhao = strings.replace("【书号】：", "").strip()
            elif strings.find("【标准状态】：") > -1:
                legal_status = strings.replace("【标准状态】：", "").strip()
            elif strings.find("【英文书名】：") > -1:
                title_alternative = strings.replace("【英文书名】：", "").strip()
                title_alternative = title_alternative.replace("标准数据-导入-含中电真实分类信息.xls","")
            elif strings.find("【发布日期】：") > -1:
                date_created = strings.replace("【发布日期】：", "").strip()
            elif strings.find("【实施日期】：") > -1:
                date_impl = strings.replace("【实施日期】：", "").strip()
            elif strings.find("【发布单位】：") > -1:
                creator_release = strings.replace("【发布单位】：", "").strip()
            elif strings.find("【起草单位】：") > -1:
                creator_drafting = strings.replace("【起草单位】：", "").strip()
            elif strings.find("【主要起草人】：") > -1:
                creator = strings.replace("【主要起草人】：", "").strip()
            elif strings.find("【简介】：") > -1:
                description = strings.replace("【简介】：", "").strip()
            elif strings.find("【页数】：") > -1:
                page = strings.replace("【页数】：", "").strip()
            elif strings.find("【出版社】：") > -1:
                publisher = strings.replace("【出版社】：", "").strip()
            elif strings.find("【标准类别】：") > -1:
                description_type = strings.replace("【标准类别】：", "").strip()
            elif strings.find("您尚未购买此资源") > -1:
                pass
            else:
                self.logger.info(strings)
                sys.exit("出现未解析的字段,停止程序检查")

        sub_db_id = "00135"
        product = "YUETONG"
        sub_db = "BZ"
        provider_zt = "yuetongstandard"
        provider = "CCPCL"

        date_created = date_created.replace("月", "")
        date_impl = date_impl.replace("月", "")

        date_created_list = date_created.split("-")
        date_created_list[1] = str(BaseString.chinese2digits(date_created_list[1])).zfill(2)
        date_created = "-".join(date_created_list)

        date_impl_list = date_impl.split("-")
        date_impl_list[1] = str(BaseString.chinese2digits(date_impl_list[1])).zfill(2)
        date_impl = "-".join(date_impl_list)

        date_created = MDateTimeUtils.date_format(date_created, "%d-%m-%Y", "%Y%m%d")
        date_impl = MDateTimeUtils.date_format(date_impl, "%d-%m-%Y", "%Y%m%d")

        date = date_created[:4]

        creator_drafting = creator_drafting.replace("，", ";").replace(",", ";")
        creator_drafting = BaseString.cleanSemicolon(creator_drafting)

        creator = creator.replace("、", ";").replace(" ", ";").replace(",", ";").replace("，", ";").replace("　", ";")
        creator = BaseString.cleanSemicolon(creator)

        bacth = MDateTimeUtils.get_today_date_strings() + "00"
        type_ = "5"
        medium = "2"

        country = "CN"
        language = "ZH"

        url = "http://zt.yuetong.cn/rmjt/fg/article/otherarticle.html?sign=detail&articleid={}".format(rawid)
        provider_url = provider_zt + "@" + url
        provider_id = provider_zt + "@" + rawid

        pagecount = page
        lngid = GetLngid(sub_db_id, rawid)

        self.Listpara.append((lngid, rawid, title, country, language,
                              provider_zt, bacth, type_, medium,
                              provider_url, provider_id, date, date_created,
                              publisher, creator_release, description, description_type,
                              date_impl, legal_status, creator_drafting, creator, pagecount,
                              page, title_alternative))


if __name__ == "__main__":
    """
    本库不解析a层
    """
    para = ParaZTA()
    para.select_files()
